<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>获取表单元素的值 - 受控组件</title>
</head>
<body>
    <div id="root"> </div>

    <script src="../js/react.development.js"></script>
    <script src="../js/react-dom.development.js"></script>
    <script src="../js/babel.min.js"></script>

    <script type="text/babel">
        class App extends React.Component{
            //1. 声明状态
            state = {
                username: '',
                password: ''
            }

            render(){
                return <form action="">
                        <h2>登录</h2>
                        {/*2. 为 input 元素添加状态值  onChange  on当...时候   change 改变  */}
                        用户名: <input type="text" value={this.state.username} onChange={this.saveUser} /><br/>
                        密码: <input type="password" value={this.state.password} onChange={this.savePass}  /><br/>
                        <input type="submit" value="登录" onClick={this.login} />
                    </form>
            }

            //3. 保存用户名的事件
            saveUser = (e) => {
                // console.log(e.target.value); // 保存的是 input 元素应该要变成的值
                //修改 username 的状态值
                this.setState({
                    username: e.target.value
                })
            }

            //保存密码的事件
            savePass = (e) => {
                this.setState({
                    password: e.target.value
                })
            }

            //声明事件回调
            login = (e) => {
                e.preventDefault();
                //显示账号密码
                console.log('用户名: '+ this.state.username , '密码为: '+this.state.password);
                //清空表单的值
                this.setState({
                    username: '',
                    password: ''
                })
            }
        }

        //渲染
        ReactDOM.render(<App/>, document.querySelector("#root"));
    </script>
</body>
</html>